﻿using AutoBlogger.Properties;
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using System.IO;
using System.IO.Compression;
using HtmlAgilityPack;
using System.Web;
using AutoBlogger.DB;
using Newtonsoft.Json.Linq;

namespace AutoBlogger.Tool
{
    internal class NetClient
    {
        internal static void PostBlogToBlogger(BlogModel blog)
        {
            try
            {
                byte[] content = Encoding.UTF8.GetBytes(
                    Settings.Default.Content1 +
                    blog.Title +
                    Settings.Default.Content2 +
                    blog.Content +
                    Settings.Default.Content3);

                WebClient wClient = new WebClient();
                wClient.Proxy = new WebProxy(Settings.Default.Proxy);
                wClient.Headers["Accept"] = "*/*";
                wClient.Headers["Accept-Charset"] = "GBK,utf-8;q=0.7,*;q=0.3";
                wClient.Headers["Accept-Encoding"] = "gzip,deflate,sdch";
                wClient.Headers["Accept-Language"] = "en-US,en;q=0.8,zh-CN;q=0.6,zh;q=0.4";
                wClient.Headers["Cookie"] = Settings.Default.Cookie;
                wClient.Headers["Content-Type"] = "application/json; charset=UTF-8";
                wClient.Headers["Origin"] = "http://www.blogger.com";
                wClient.Headers["Referer"] = "http://www.blogger.com/blogger.g?blogID=6214623746437766930";
                wClient.Headers["User-Agent"] = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.13 (KHTML, like Gecko) Chrome/24.0.1290.1 Safari/537.13";
                wClient.Headers["X-GWT-Module-Base"] = "http://www.blogger.com/static/v1/gwt/";
                wClient.Headers["X-GWT-Permutation"] = "259F03DCCFA4E67558AE56C1A1BC285F";
                //wClient.Headers[""] = "";
                string s = Encoding.UTF8.GetString(wClient.UploadData(Settings.Default.BlogPostUrl, "post", content));
            }
            catch (Exception ex)
            {
                LogError.LogErrorToFile(ex);
            }
        }

        static Stream GetRecipe(uint recipeNumber)
        {
            string url = string.Format(Settings.Default.RecipeUrl, recipeNumber);
            WebHeaderCollection webHeaderList = new WebHeaderCollection();
            webHeaderList["Accept"] = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
            webHeaderList["Accept-Encoding"] = "gzip";
            webHeaderList["Accept-Charset"] = "utf-8";
            webHeaderList["User-Agent"] = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.94 Safari/537.4";
            try
            {
                WebClient wc = new WebClient()
                    {
                        Headers = webHeaderList,
                        Encoding = Encoding.UTF8
                    };

                byte[] resultByte = wc.DownloadData(url);
                GZipStream gzip = new GZipStream(new MemoryStream(resultByte), CompressionMode.Decompress);
                return gzip;
            }
            catch (Exception ex)
            {
                LogError.LogErrorToFile(ex);
                return null;
            }
        }

        internal static string TranslateText(string text)
        {
            WebHeaderCollection webHeaderList = new WebHeaderCollection();
            webHeaderList["X-Requested-With"] = "XMLHttpRequest";
            webHeaderList["Accept-Encoding"] = "gzip";
            webHeaderList["Accept-Language"] = "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3";
            webHeaderList["User-Agent"] = "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:16.0) Gecko/20100101 Firefox/16.0";
            webHeaderList["Pragma"] = "no-cache";
            webHeaderList["DNT"] = "1";
            webHeaderList["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8";
            webHeaderList["Accept"] = "application/json, text/javascript, */*; q=0.01";
            //webHeaderList["Cookie"] = "YODAO_MOBILE_ACCESS_TYPE:1;SESSION_FROM_COOKIE:fanyiweb;OUTFOX_SEARCH_USER_ID:1272566773@119.40.37.156;JSESSIONID:abc_LtUrVpsGV4wptD3Rt;_ntes_nnid:dc43fbc4d3071f452f0a4cbabf0702f2,1352771383031;__ntes__test__cookies:1352771383026";

            try
            {
                WebClient wc = new WebClient();
                wc.Encoding = Encoding.UTF8;

                wc.Headers = webHeaderList;
                string translatBody = string.Format(Settings.Default.TranslateBody, HttpUtility.UrlEncode(
                    UnEscape(
                    HttpUtility.UrlEncode(
                    text))));
                byte[] responseBytes = wc.UploadData(Settings.Default.TranslateUrl, Encoding.UTF8.GetBytes(translatBody));

                string jsonResponse = UnZipHtml(responseBytes);
                return jsonResponse;
            }
            catch (Exception ex)
            {
                LogError.LogErrorToFile(ex);
                return null;
            }
        }

        internal static string UnZipHtml(byte[] responseBytes)
        {
            using (GZipStream gzip = new GZipStream(new MemoryStream(responseBytes),
                CompressionMode.Decompress))
            {
                StreamReader reader = new StreamReader(gzip, Encoding.UTF8);

                string jsonResponse = reader.ReadToEnd();
                reader.Close();
                gzip.Close();
                return jsonResponse;
            }
        }

        internal static string getBlogFromJson(string json)
        {
            JObject rss = JObject.Parse(json);
            JArray translateResult = rss["translateResult"] as JArray;
            string title = translateResult[0][0]["tgt"].ToString();
            StringBuilder sb = new StringBuilder();
            for (int i = 1; i < translateResult.Count; i++)
            {
                sb.Append(translateResult[i][0]["tgt"].ToString());
            }
            string body = sb.ToString();
            return string.Empty;
        }

        internal static byte[] DownloadImage(string url)
        {
            byte[] data = null;

            using (WebClient wClient = new WebClient())
            {
                try
                {
                    data = wClient.DownloadData(url);
                }
                catch (WebException ex)
                {

                }
            }

            return data;
        }

        #region Escape的加密、解密

        /// <summary>

        /// Escape的加密

        /// </summary>

        /// <param name="str"></param>

        /// <returns></returns>

        public static string Escape(string str)
        {

            if (str == null)

                return String.Empty;



            StringBuilder sb = new StringBuilder();

            int len = str.Length;



            for (int i = 0; i < len; i++)
            {

                char c = str[i];



                //everything other than the optionally escaped chars _must_ be escaped 

                if (Char.IsLetterOrDigit(c) || c == '-' || c == '_' || c == '/' || c == '\\' || c == '.')

                    sb.Append(c);

                else

                    sb.Append(Uri.HexEscape(c));

            }



            return sb.ToString();

        }

        /// <summary>

        /// Escape的解密

        /// </summary>

        /// <param name="str"></param>

        /// <returns></returns>

        public static string UnEscape(string str)
        {

            if (str == null)

                return String.Empty;



            StringBuilder sb = new StringBuilder();

            int len = str.Length;

            int i = 0;

            while (i != len)
            {

                if (Uri.IsHexEncoding(str, i))

                    sb.Append(Uri.HexUnescape(str, ref i));

                else

                    sb.Append(str[i++]);

            }



            return sb.ToString();

        }

        #endregion
    }
}
